var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");

var cwpRoute = require("./routes/cwpRoute");
var usersRouter = require("./routes/users");
var startRouter = require("./routes/start");
var uploadRouter = require("./routes/upload");
var cors = require("cors");
var bodyParser = require("body-parser");

var app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use("/upload", express.static("upload"));
// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");

app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));

app.use("/cwp", cwpRoute);
app.use("/users", usersRouter);
app.use("/start", startRouter);
app.use("/upload", uploadRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

let { messagemodel } = require("./model/cwp");
const ws = require("nodejs-websocket");
let server = ws
  .createServer(function (connect) {
    connect.on("error", function (err) {
      console.error("Connection error:", err);
    });
    connect.on("text", async function (str) {
      try {
        const data = JSON.parse(str);
        if (data.type === "heartbeat") {
          console.log("收到心跳消息");
          // 心跳消息，忽略处理
          return;
        }
        // 插入数据库
        console.error("Error adding data to the database:", error);
      }
    });
  })
  .listen(7777);

async function sendToConnection(connection, message) {
  return new Promise((resolve, reject) => {
    connection.sendText(message, (error) => {
      console.log(message, "----------------------");
      if (error) {
        reject(error);
      } else {
        resolve();
      }
    });
  });
}



module.exports = app;
